from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from datetime import datetime
import time

from app.api import deps
from app.schemas import package_order as schemas
from app.database.models.erp import PackageOrder as PackageOrderModel
from app.database.models.base import User
from app.schemas.package_order import PackageOrder as PackageOrderSchema, PackageOrderList

router = APIRouter()

def generate_order_number() -> str:
    """生成订单号：年月日时分秒+3位随机数"""
    timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
    random_num = str(int(time.time() * 1000))[-3:]
    return f"PKG{timestamp}{random_num}"

@router.get("/", response_model=List[schemas.PackageOrder])
def get_package_orders(
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_agent_user),
    skip: int = 0,
    limit: int = 100
):
    """获取打包订单列表"""
    orders = db.query(PackageOrderModel)\
        .filter(PackageOrderModel.work_area_id == current_user.workarea_id)\
        .offset(skip)\
        .limit(limit)\
        .all()
    return orders

@router.post("/", response_model=schemas.PackageOrder)
def create_package_order(
    *,
    db: Session = Depends(deps.get_db),
    order_in: schemas.PackageOrderCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """创建新的打包订单"""
    try:
        order_data = order_in.dict()
        order_data.update({
            "work_area_id": current_user.workarea_id,
            "order_number": generate_order_number(),
            "status": "draft",
            "created_at": datetime.now(),
            "created_user_name": current_user.username
        })

        order = PackageOrderModel(**order_data)
        db.add(order)
        db.commit()
        db.refresh(order)
        return order
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/{order_id}", response_model=schemas.PackageOrder)
def get_package_order(
    order_id: int,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取特定订单详情"""
    try:
        order = db.query(PackageOrderModel).filter(PackageOrderModel.ID == order_id).first()
        if not order:
            raise HTTPException(status_code=404, detail="Order not found")

        # 检查权限
        if current_user.role != "admin" and order.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        return order
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/{order_id}", response_model=schemas.PackageOrder)
def update_package_order(
    *,
    db: Session = Depends(deps.get_db),
    order_id: int,
    order_in: schemas.PackageOrderUpdate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """更新订单信息"""
    try:
        order = db.query(PackageOrderModel).filter(PackageOrderModel.ID == order_id).first()
        if not order:
            raise HTTPException(status_code=404, detail="Order not found")

        # 检查权限
        if current_user.role != "admin" and order.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 更新订单
        update_data = order_in.dict(exclude_unset=True)
        
        for field, value in update_data.items():
            setattr(order, field, value)

        db.add(order)
        db.commit()
        db.refresh(order)
        return order
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/{order_id}")
def delete_package_order(
    *,
    db: Session = Depends(deps.get_db),
    order_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """删除订单"""
    try:
        order = db.query(PackageOrderModel).filter(PackageOrderModel.ID == order_id).first()
        if not order:
            raise HTTPException(status_code=404, detail="Order not found")

        # 检查权限
        if current_user.role != "admin" and order.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        db.delete(order)
        db.commit()
        return {"ok": True}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e)) 